# Create your views here.
from rest_framework.viewsets import ModelViewSet
from user.serializers.register_serializers import *
from django.views import View

from django.http import JsonResponse
import re, random

from django_redis import get_redis_connection
import logging

from rest_framework.generics import ListAPIView

from user.serializers.personalserializer import *

logger = logging.getLogger('then_power')


class CodeView(View):
    """获取验证码"""

    def get(self, request, mobile):
        # 判断参数是否缺少
        if not all([mobile]):
            return JsonResponse({'success': False,
                                 'errmsg': '缺少参数'})
        # 校验手机号是否输入正确
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'success': False,
                                 'message': '手机号输入错误'
                                 })
        # 生成验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        # 链接redis
        redis_conn = get_redis_connection('verify_code')

        # 0. 从redis中获取一个60s的字段, 判断该字段是否存在
        flag = redis_conn.get('send_flag_%s' % mobile)

        if flag:
            return JsonResponse({'code': 400,
                                 'errmsg': "请勿频发发送短信"})
        # 生成管道对象
        pl = redis_conn.pipeline()
        # 保存在redis
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # ccp_send_sms_code.delay(mobile,sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 123)
        pl.execute()
        return JsonResponse({'success': True,
                             'sms_code': sms_code,
                             'message': 'ok'
                             })


class RegisterView(ModelViewSet):
    """注册"""
    queryset = User.objects.all()
    serializer_class = RegisterSerializer


class UserListView(ListAPIView):
    """用户中心"""
    queryset = User.objects.all()
    serializer_class = PersonalSerializer
